"use strict";
// 引入crypto
const crypto = require("crypto");
const Controller = require("egg").Controller;

class HomeController extends Controller {
  //后台首页
  async index(){
    const {ctx } = this;
    await ctx.render('admin/home/index.html')
  }
  //登录页
  async login() {
    let { ctx, app } = this;
    let toast = ctx.cookies.get('toast',{ encrypt: true });
        toast = toast ? JSON.parse(toast) : null
        await ctx.render('admin/home/login.html',{
            toast
        });
  }

  //登录逻辑
  async loginevent() {
    let { ctx, app } = this;
    //参数验证
    ctx.validate({
      username: {
        type: "string",
        required: true,
        desc: "用户名",
      },
      password: {
        type: "string",
        required: true,
        desc: "密码",
      },
    });
    let { username, password } = ctx.request.body;
    let manager = await app.model.Manager.findOne({
      where: {
        username,
      },
    });
    if (!manager) {
      ctx.throw(400, "该管理员不存在");
    }
    //密码验证
    await ctx.checkPassword(password,manager.password);
    //存储到session中
    ctx.session.auth = manager;
    return ctx.apiSuccess('ok');
  }
  //退出登录
  async logout(){
    const { ctx } = this;
    // 清除session
    ctx.session.auth = null
    ctx.toast('退出登录成功','success')
    ctx.redirect(`/admin/login`);
  }
}

module.exports = HomeController;
